/*
 * SPDX-License-Identifier: Apache-2.0
 * Copyright Red Hat Inc. and Hibernate Authors
 */
package org.hibernate.id.enhanced;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.hibernate.HibernateException;
import org.hibernate.id.IntegralDataTypeHolder;

import org.jboss.logging.Logger;

/**
 * Slight variation from {@link HiLoOptimizer}, maintaining compatibility with the values generated by the
 * legacy Hibernate hilo based generators.
 *
 * @author Steve Ebersole
 */
public class LegacyHiLoAlgorithmOptimizer extends AbstractOptimizer {
	private static final Logger log = Logger.getLogger( LegacyHiLoAlgorithmOptimizer.class );

	private final long initialMaxLo;

	private static class GenerationState {
		private long maxLo;
		private long lo;
		private IntegralDataTypeHolder hi;

		private IntegralDataTypeHolder lastSourceValue;
		private IntegralDataTypeHolder value;
	}

	/**
	 * Constructs a {@code LegacyHiLoAlgorithmOptimizer}
	 *
	 * @param returnClass The Java type of the values to be generated
	 * @param incrementSize The increment size.
	 */
	public LegacyHiLoAlgorithmOptimizer(Class<?> returnClass, int incrementSize) {
		super( returnClass, incrementSize );
		if ( incrementSize < 1 ) {
			throw new HibernateException( "increment size cannot be less than 1" );
		}
		if ( log.isTraceEnabled() ) {
			log.tracev( "Creating hilo optimizer (legacy) with [incrementSize={0}; returnClass={1}]", incrementSize, returnClass.getName() );
		}
		initialMaxLo = incrementSize;
	}

	@Override
	public Serializable generate(AccessCallback callback) {
		lock.lock();
		try {
			final GenerationState generationState = locateGenerationState( callback.getTenantIdentifier() );

			if ( generationState.lo > generationState.maxLo ) {
				generationState.lastSourceValue = callback.getNextValue();
				generationState.lo = generationState.lastSourceValue.eq( 0 ) ? 1 : 0;
				generationState.hi = generationState.lastSourceValue.copy().multiplyBy( generationState.maxLo + 1 );
			}
			generationState.value = generationState.hi.copy().add( generationState.lo++ );
			return generationState.value.makeValue();
		}
		finally {
			lock.unlock();
		}

	}

	/**
	 * Use a lock instead of the monitor lock to avoid pinning when using virtual threads.
	 */
	private final Lock lock = new ReentrantLock();
	private GenerationState noTenantState;
	private Map<String,GenerationState> tenantSpecificState;

	private GenerationState locateGenerationState(String tenantIdentifier) {
		if ( tenantIdentifier == null ) {
			if ( noTenantState == null ) {
				noTenantState = createGenerationState();
			}
			return noTenantState;
		}
		else {
			GenerationState state;
			if ( tenantSpecificState == null ) {
				tenantSpecificState = new ConcurrentHashMap<>();
				state = createGenerationState();
				tenantSpecificState.put( tenantIdentifier, state );
			}
			else {
				state = tenantSpecificState.get( tenantIdentifier );
				if ( state == null ) {
					state = createGenerationState();
					tenantSpecificState.put( tenantIdentifier, state );
				}
			}
			return state;
		}
	}

	private GenerationState createGenerationState() {
		final GenerationState state = new GenerationState();
		state.maxLo = initialMaxLo;
		state.lo = initialMaxLo + 1;
		return state;
	}

	private GenerationState noTenantGenerationState() {
		if ( noTenantState == null ) {
			throw new IllegalStateException( "Could not locate previous generation state for no-tenant" );
		}
		return noTenantState;
	}

	@Override
	public IntegralDataTypeHolder getLastSourceValue() {
		lock.lock();
		try {
			return noTenantGenerationState().lastSourceValue.copy();
		}
		finally {
			lock.unlock();
		}
	}

	@Override
	public boolean applyIncrementSizeToSourceValues() {
		return false;
	}

	/**
	 * Getter for property 'lastValue'.
	 * <p>
	 * Exposure intended for testing purposes.
	 *
	 * @return Value for property 'lastValue'.
	 */
	public IntegralDataTypeHolder getLastValue() {
		lock.lock();
		try {
			return noTenantGenerationState().value;
		}
		finally {
			lock.unlock();
		}
	}
}
